#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>

void childRun()
{
    int cnt = 5;
    while(cnt--)
    {
        printf("I am a child process, pid: %d, ppid: %d\n", getpid(), getppid());
        sleep(2);
    }
}

int main()
{
    printf("father process is running... pid: %d, ppid: %d\n", getpid(), getppid());
    
    pid_t id = fork();
    if(id == 0)
    {
        // child
        childRun();
        printf("child process is running, pid: %d, ppid: %d\n", getpid(), getppid());
        sleep(2);
        exit(123);
    }

    // father
    // 通过循环，进行非阻塞轮询
    while(1)
    {
        int status = 0;
        pid_t rid = waitpid(id, &status, WNOHANG);
        if(rid == 0)
        {
            printf("child process not quit, check next time!\n");
        }
        else if(rid > 0)
        {   
            // 已经等待成功了，检测一下退出情况
            if(WIFEXITED(status))
                printf("child quit success! child exit code: %d\n", WEXITSTATUS(status));
            else
                printf("child quit unnormal!\n");

            break;
        }
        else
        {
            // 等待失败
            printf("wait failed!\n");
            break;
        }
    }

    return 0;
}

